package puyu.manage.service.security.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import puyu.manage.service.SysUser.service.SysUserServiceI;
import puyu.manage.service.security.LoginUser;
import puyu.manage.service.utils.MessageUtils;
import puyu.manage.service.utils.StringUtils;
import puyu.manage.service.utils.enums.UserStatus;
import puyu.manage.service.utils.except.BaseException;

import java.util.Map;

/**
 * 用于加载用户信息 实现UserDetailsService接口，或者实现AuthenticationUserDetailsService接口
 */

@Service
public class CasUserDetailsService implements AuthenticationUserDetailsService<CasAssertionAuthenticationToken> {

	private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

	@Autowired
	private SysUserServiceI userService;

	@Override
	public UserDetails loadUserDetails(CasAssertionAuthenticationToken token) throws UsernameNotFoundException {
		String username = token.getName();
		Map<String,Object> user = userService.selectUserInfoByUserName(username);
		if (StringUtils.isNull(user))
		{
			log.info("登录用户：{} 不存在.", username);
			throw new UsernameNotFoundException(MessageUtils.message("A0100",username));
		}
		else if ("1".equals(user.get("is_del")))
		{
			log.info("登录用户：{} 已被删除.", username);
			throw new BaseException(MessageUtils.message("A0111",username));
		}
		else if (UserStatus.DISABLE.getCode().equals(user.get("status")))
		{
			log.info("登录用户：{} 已被停用.", username);
			throw new BaseException(MessageUtils.message("A0112",username));
		}
		else if (UserStatus.LOCK.getCode().equals(user.get("status")))
		{
			log.info("登录用户：{} 已被锁定.", username);
			throw new BaseException(MessageUtils.message("A0114",username));
		}
		return createLoginUser(user);
	}

	public UserDetails createLoginUser(Map<String,Object> user) {
		return new LoginUser(user);
	}
}
